package com.avfh.netcard.interceptor;

import com.avfh.netcard.common.Constant;
import com.avfh.netcard.listener.StartupListener;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * Created by lws on 2017/6/27.
 */
@Component
public class WxIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("********************************" + "openId拦截器");
        WxMpServiceImpl wxMpService = StartupListener.wxService;
        if (request.getSession().getAttribute("openId") != null)
            return true;
        String code = request.getParameter("code");
        if (StringUtils.isEmpty(code)) {
            Enumeration<String> enu = request.getParameterNames();
            String params = "";
            while (enu.hasMoreElements()) {
                String paraName = enu.nextElement();
                params += paraName + "=" + request.getParameter(paraName) + "&";
            }

            String path = request.getScheme() + "://" + request.getServerName() +
                    request.getContextPath() + request.getServletPath();

            if (!StringUtils.isEmpty(params)) {
                params = "?" + params.substring(0, params.length() - 1);
                path += params;
            }
            System.out.println(path);

            String url = wxMpService.oauth2buildAuthorizationUrl(path, Constant.SCOPE, null);
            System.out.println("yyyyyyyyyyyyyyyyyyyy" + url);
            response.sendRedirect(url);
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
